<script setup lang="ts">
import { QUESTION_TYPE_CONFIG } from '@/views/exam/template/info/config';
import { ProjectForm } from '@/api/exam/project/types';
import * as echarts from 'echarts';
import { EChartsOption } from 'echarts';

interface Props {
  projectForm: any | ProjectForm;
  answerList: any;
  segmentedValue: string;
}

const props = withDefaults(defineProps<Props>(), {
  segmentedValue: '',
  projectForm: {
    survey: {
      children: []
    }
  },
  answerList: []
});
const projectForm = ref<ProjectForm>(props.projectForm);
const answerList = ref<any>(props.answerList);
watch(() => props.segmentedValue, () => {
  projectForm.value = props.projectForm;
  answerList.value = props.answerList;
});

// 过滤题目类型
const filteredQuestions = computed(() => {
  return projectForm.value.survey.children.filter(q =>
    ['Radio', 'TrueFalse', 'Checkbox'].includes(q.type)
  );
});
// echarts
const chartRefs = ref<any>([]);

// 统计数据结构
interface QuestionStat {
  options: Array<{
    id: string
    title: string
    count: number
    percent: number
  }>;
  totalRespondents: number;
}

const questionStats = ref<QuestionStat[]>([]);
const columns = ref<any>([
  { title: '选项', dataIndex: 'title', align: 'center' },
  { title: '选择人数', dataIndex: 'count', align: 'center' },
  { title: '占比', dataIndex: 'percent', align: 'center' }
]);
// 初始化图表
const initChart = (dom: HTMLElement, index: number) => {
  const chart = echarts.init(dom);
  const { options } = questionStats.value[index];

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any[]) => {
        const data = params[0];
        return `${data.name}<br/>选择比例: ${data.value.toFixed(2)}%`;
      }
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value: number) => `${value.toFixed(1)}%`,
        fontWeight: 'bold'
      },
      max: 100 // 设置最大值为100%
    },
    yAxis: {
      type: 'category',
      data: options.map(o => o.title),
      axisLabel: {
        fontStyle: 'normal',
        width: 150,
        overflow: 'truncate',
        fontWeight: 'bold'
      }
    },
    series: [{
      type: 'bar',
      data: options.map(o => o.percent),
      itemStyle: {
        color: '#1890ff',
        borderRadius: [0, 5, 5, 0]
      },
      label: {
        show: true,
        position: 'right',
        formatter: ({ value }: any) => `${value.toFixed(1)}%`,
        fontWeight: 'bold'
      }
    }],
    grid: {
      left: '25%',
      right: '8%',
      containLabel: true
    }
  };
  chart.setOption(option);
  return chart;
};

// 统计单个题目的选项数据
const getQuestionStats = () => {
  // 如果试卷开启了随机抽题，那么跳过
  if (projectForm.value.setting.examSetting.randomProject) {
    return questionStats.value = [];
  }
  questionStats.value = filteredQuestions.value.map(question => {
    const options = question.children.map(option => {
      const count = answerList.value.reduce((acc, answer) =>
        acc + (answer.answer[question.id]?.[option.id] ? 1 : 0), 0);
      return { id: option.id, title: option.title, count };
    });

    const totalRespondents = answerList.value.filter(answer =>
      Object.keys(answer.answer[question.id] || {}).length > 0
    ).length;

    // 计算百分比
    const optionsWithPercent = options.map(option => ({
      ...option,
      percent: totalRespondents > 0
        ? (option.count / totalRespondents) * 100
        : 0
    }));

    return {
      options: optionsWithPercent,
      totalRespondents
    };
  });
};

onMounted(() => {
  getQuestionStats();
  // 等待 DOM 更新后初始化图表
  setTimeout(() => {
    filteredQuestions.value.forEach((_, index) => {
      const dom = chartRefs.value[index];
      if (dom) initChart(dom as HTMLElement, index);
    });
  }, 0);
});
</script>

<template>
  <div>
    <div v-for="(item,index) in filteredQuestions" :key="item.id">
      <a-row :gutter="12">
        <a-col :span="12">
          {{ item.title }}
          <div
            :ref="el => chartRefs[index] = el"
            class="chart" style="height: 250px"
          ></div>
        </a-col>
        <a-col :span="12">
          <a-flex justify="space-between">
            <div>问题类型: {{ QUESTION_TYPE_CONFIG[item.type].label }}</div>
            <div>{{ questionStats[index]?.totalRespondents || 0 }} 条数据</div>
          </a-flex>

          <a-table :columns="columns" :data-source="questionStats[index]?.options"
                   :pagination="false" size="small">
            <template #bodyCell="{ column, text, record }">
              <!--                  <template v-if="column.dataIndex === 'percent'">-->
              <!--                    {{ calculatePercent(record.count, questionStats[index]?.total) }}-->
              <!--                  </template>-->
              <template v-if="column.dataIndex === 'percent'">
                {{ record.percent.toFixed(2) }}%
              </template>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<style scoped lang="scss">

</style>
